﻿using System.Net;

namespace RpcHelper.Http
{
        internal class Helper
        {
                private static string _GetHeaderFileName (WebHeaderCollection hearder)
                {
                        string val = null;
                        foreach (string i in hearder)
                        {
                                if (i == "Content-Disposition")
                                {
                                        val = hearder[i];
                                        break;
                                }
                        }
                        if (val == null)
                        {
                                return null;
                        }
                        int begin = val.IndexOf ("filename=");
                        if (begin == -1)
                        {
                                return null;
                        }
                        begin += 10;
                        int end = val.IndexOf ("\"", begin);
                        return val.Substring (begin, end - begin);
                }
                public static string GetFileType (HttpWebResponse response)
                {
                        string type = response.ContentType;
                        if (type.IsNull () || type == "application/octet-stream")
                        {
                                return _GetHeaderFileName (response.Headers);
                        }
                        type = HttpHeaderHelper.GetExtension (type);
                        if (type != null)
                        {
                                return type;
                        }
                        string val= _GetHeaderFileName (response.Headers);
                        if(val != null)
                        {
                                return val;
                        }
                        else if(type.LastIndexOf("-") == -1)
                        {
                                return Tools.GetFileExtension (type);
                        }
                        return null;
                }
        }
}
